package com.shiguiwu.springboot3.redis.mq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description: list
 * @author: stone
 * @date: Created by 2023/12/15 11:31
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.redis.mq
 */
@Component
public class RedisListMQService {

    public static String QUEUE_KEY = "QUEUE_KEY";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void send(String msg) {
        redisTemplate.opsForList().leftPush(QUEUE_KEY, msg);
    }


    public void listener() {
        // 消费者线程
        new Thread(() -> {
            while (true) {
                // BRPOP是一个阻塞的列表弹出原语。它按参数key的顺序检查，删除，返回第一个非空列表的尾部元素。
                // 这里我们设置超时为0，表示无限等待直到有元素可以弹出
                String message = (String) redisTemplate.opsForList().rightPop(QUEUE_KEY);
                if (message == null) {
                    continue;
                }

                System.out.println("Received: " + message);
            }
        }).start();
    }


}
